package com.micro.train.service.impl;

import com.micro.train.entity.Train;
import com.micro.train.repository.TrainRepository;
import com.micro.train.service.InventoryScheduleService;
import com.micro.train.service.TrainSeatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

/**
 * 库存管理定时任务服务实现
 */
@Slf4j
@Service
public class InventoryScheduleServiceImpl implements InventoryScheduleService {
    
    @Autowired
    private TrainSeatService trainSeatService;
    
    @Autowired
    private TrainRepository trainRepository;
    
    /**
     * 每日凌晨2点执行库存窗口滚动
     */
    @Scheduled(cron = "0 0 2 * * ?")
    @Override
    public void dailyRollInventoryWindow() {
        log.info("开始执行每日库存窗口滚动任务");
        try {
            LocalDate newBaseDate = LocalDate.now();
            manualRollInventoryWindow(newBaseDate);
            log.info("每日库存窗口滚动任务执行完成，新基准日期：{}", newBaseDate);
        } catch (Exception e) {
            log.error("每日库存窗口滚动任务执行失败", e);
        }
    }
    
    /**
     * 每日凌晨3点清理过期库存记录
     */
    @Scheduled(cron = "0 0 3 * * ?")
    @Override
    public void cleanupExpiredInventory() {
        log.info("开始执行清理过期库存记录任务");
        try {
            LocalDate expireDate = LocalDate.now().minusDays(7);
            trainSeatService.cleanupExpiredInventory(expireDate);
            log.info("清理过期库存记录任务执行完成，过期日期：{}", expireDate);
        } catch (Exception e) {
            log.error("清理过期库存记录任务执行失败", e);
        }
    }
    
    /**
     * 系统启动时初始化所有列车的库存窗口
     */
    @Scheduled(initialDelay = 10000, fixedDelay = Long.MAX_VALUE) // 系统启动10秒后执行一次
    @Override
    public void initializeAllTrainInventories() {
        log.info("开始初始化所有列车的库存窗口");
        try {
            List<Train> trains = trainRepository.selectList(null);
            LocalDate baseDate = LocalDate.now();
            
            for (Train train : trains) {
                try {
                    trainSeatService.initializeInventoryWindow(train.getTrainId(), baseDate);
                    log.info("列车 {} 库存窗口初始化完成", train.getTrainNumber());
                } catch (Exception e) {
                    log.error("列车 {} 库存窗口初始化失败", train.getTrainNumber(), e);
                }
            }
            
            log.info("所有列车库存窗口初始化完成");
        } catch (Exception e) {
            log.error("初始化所有列车库存窗口失败", e);
        }
    }
    
    @Override
    public void manualRollInventoryWindow(LocalDate newBaseDate) {
        log.info("开始手动滚动库存窗口，新基准日期：{}", newBaseDate);
        try {
            trainSeatService.rollInventoryWindow(newBaseDate);
            log.info("手动滚动库存窗口完成");
        } catch (Exception e) {
            log.error("手动滚动库存窗口失败", e);
            throw e;
        }
    }
}
